package bean.managed;

import entity.SystemUserEntity;
import bean.managed.util.JsfUtil;
import bean.managed.util.PaginationHelper;
import bean.session.RoleEntityFacade;
import bean.session.SystemUserEntityFacade;

import entity.DepartmentEntity;
import entity.PersonEntity;
import entity.RoleEntity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.faces.validator.ValidatorException;
import managedbean.AbstractBacking;
import org.apache.log4j.Logger;
import type.UserTitle;
import util.Fixtures.Department;
import util.Fixtures.Role;
import util.PasswordEncryptor;
import util.SecureRandomNumberGenerator;

@ManagedBean(name = "systemUserEntityController")
@SessionScoped
public class SystemUserEntityController extends AbstractBacking implements Serializable {

    private Logger log = Logger.getLogger(getClass());
    private SystemUserEntity current;
    private DataModel items = null;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private List<PersonEntity> searchResult = new ArrayList<PersonEntity>();
    @EJB
    public bean.session.SystemUserEntityFacade ejbFacade;
    @EJB
    public bean.session.DepartmentEntityFacade departmentFacade;
    @EJB
    private bean.session.ContactEntityFacade contactFacade;
    @EJB
    private RoleEntityFacade roleFacade;
    
    @ManagedProperty(value = "#{contactEntityController}")
    private ContactEntityController contactEntityController;
    private String searchField = "all";
    private String userSearchInput;
    private DepartmentEntity searchDepartment;
    private boolean diaplaySearchResult;

    public SystemUserEntityController() {
    }

    public SystemUserEntity getSelected() {
        if (current == null) {
            current = new SystemUserEntity();
            selectedItemIndex = -1;
        }
        return current;
    }

    private SystemUserEntityFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "/entities/systemUserEntity/List.xhtml?faces-redirect=true";
    }

    private void resetContactAndAddresses() {
        getContactEntityController().setupCurrent(current.getContact());
        System.out.println("After Reset Contact method");
    }

    public String prepareView() {
//        current = (SystemUserEntity) getItems().getRowData();
        resetContactAndAddresses();
//        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "/entities/systemUserEntity/View.xhtml";
    }

    public String prepareCreate() {
        current = new SystemUserEntity();
        //resetContactAndAddresses();
        selectedItemIndex = -1;
        return "/entities/systemUserEntity/Register?faces-redirect=true";
    }

    public String confirm() {
        return "Confirm";
    }

    public String create() {
        try {
            createWithoutRedirect();
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("SystemUserEntityCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    private void createWithoutRedirect() throws Exception {
        resetContactAndAddresses();
        current.created(getLoginPerson());
        encryptPasswordForCurrent();
        current.getContact().setPerson(current);
        getFacade().create(current);
        updateDepartmentRoll();

        postCreateRoleAssignment();
    }

    public String prepareEdit() {
//        current = (SystemUserEntity) getItems().getRowData();
        resetContactAndAddresses();
        System.out.println("After Reset Contact");
//        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "/entities/systemUserEntity/Edit?faces-redirect=true";
    }

    public String update() {
        try {
            updateWithoutRedirect();
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("SystemUserEntityUpdated"));
            return "View";
        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    private void updateDepartmentRoll() {
        current.getDepartment().getEmployees().add(current);
        departmentFacade.edit(current.getDepartment());
    }

    public void updateWithoutRedirect() throws Exception {
        current.modified(getLoginPerson());
        getFacade().edit(current);
        updateDepartmentRoll();
    }

    public String destroy() {
        performDestroy();
        recreateModel();
        return "List";
    }

    public String activate() {
//        current = (SystemUserEntity) getItems().getRowData();
//        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            current.modified(getLoginPerson());
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("SystemUserEntityDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }
    
    public SelectItem[] getSalesExecutiveAvailableSelectOne() {
        return JsfUtil.getSelectItems((List<SystemUserEntity>)departmentFacade.findDepartmentByName(Department.Sales.getName()).getEmployees(), true);
    }

    @FacesConverter(forClass = SystemUserEntity.class, value = "systemUserConverter")
    public static class SystemUserEntityControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            SystemUserEntityController controller = (SystemUserEntityController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "systemUserEntityController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof SystemUserEntity) {
                SystemUserEntity o = (SystemUserEntity) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + SystemUserEntityController.class.getName());
            }
        }
    }

    public SystemUserEntity getCurrent() {
        return current;
    }

    public void setCurrent(SystemUserEntity current) {
        this.current = current;
    }

    public UserTitle[] getUserTitles() {
        return UserTitle.values();
    }

    public ContactEntityController getContactEntityController() {
        return contactEntityController;
    }

    public void setContactEntityController(ContactEntityController contactEntityController) {
        this.contactEntityController = contactEntityController;
    }

    public List<PersonEntity> getSearchResult() {
        return searchResult;
    }

    public void setSearchResult(List<PersonEntity> searchResult) {
        this.searchResult = searchResult;
    }

    //only use this for creating user and not by the user him/herself
    private void encryptPasswordForCurrent() {
        current.setPassword(PasswordEncryptor.encryptPassword(SecureRandomNumberGenerator.nextSecureRandomNumber()));
    }

    public void validateUserName(FacesContext context, UIComponent validate, Object value) {

        String userName = (String) value;
        if (ejbFacade.checkUserNameExist(userName)) {
            FacesMessage message = new FacesMessage();
            message.setDetail("UserName exists");
            message.setSummary("UserName exists");
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(message);
        }
    }

    public String save() {
        try {
            createWithoutRedirect();
            FacesMessage msg = new FacesMessage("Successful", "Welcome :" + current.getFirstName());
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } catch (Exception ex) {
            ex.printStackTrace();
            JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
        return "View";
    }

    //role rights assignement
    private void postCreateRoleAssignment() {
        try {
            RoleEntity employee = roleFacade.findRole(Role.Employee.getName());
            current.getRoles().add(employee);
            employee.getUsers().add(current);
            
            RoleEntity defaultDepartmentRole = roleFacade.findRole(Department.valueOf(current.getDepartment().getName()).getDefaultRole().getName());
            current.getRoles().add(defaultDepartmentRole);
            defaultDepartmentRole.getUsers().add(current);
            
            roleFacade.edit(employee);
            roleFacade.edit(defaultDepartmentRole);
            ejbFacade.edit(current);
        } catch (Exception ex) {
            JsfUtil.addErrorMessage(ex, "Error setting createdBy and modifiedBy");
        }
    }

    public String prepareSearch() {
        recreateModel();
        System.out.println("input: " + userSearchInput);
        System.out.println("searchField: " + searchField);
        System.out.println("searchDepartment: " + searchDepartment);
        List<SystemUserEntity> result = ejbFacade.searchEmployee(userSearchInput,
                searchField, searchDepartment == null ? null : searchDepartment.getId().toString());
        if (!result.isEmpty()) {
            setDiaplaySearchResult(true);
        }
        items = new ListDataModel(result);
        return "/entities/systemUserEntity/ListSearchResults?faces-redirect=true";
    }

    public boolean isDiaplaySearchResult() {
        return diaplaySearchResult;
    }

    public void setDiaplaySearchResult(boolean diaplaySearchResult) {
        this.diaplaySearchResult = diaplaySearchResult;
    }

    public String getSearchField() {
        return searchField;
    }

    public void setSearchField(String searchField) {
        this.searchField = searchField;
    }

    public String getUserSearchInput() {
        return userSearchInput;
    }

    public void setUserSearchInput(String userSearchInput) {
        this.userSearchInput = userSearchInput;
    }

    public DepartmentEntity getSearchDepartment() {
        return searchDepartment;
    }

    public void setSearchDepartment(DepartmentEntity searchDepartment) {
        this.searchDepartment = searchDepartment;
    }
}
